<template>
    <!-- 添加搜索区域 -->
    <el-card class="search-card">
        <el-form :inline="true" :model="searchForm">
            <el-form-item label="名称">
                <el-input v-model="searchForm.name" placeholder="请输入名称" clearable />
            </el-form-item>
            <el-form-item label="时间范围">
                <el-date-picker v-model="searchForm.timeRange" type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
                <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>

    <!-- 表格工具栏 -->
    <el-card class="table-card">
        <template #header>
            <div class="table-header">
                <el-button type="primary" @click="handleAdd">新增</el-button>
                <el-button type="warning" :disabled="!selectedRows.length" @click="handleBatchSend">一键发送</el-button>
                <el-button type="success" @click="handleExport">导出</el-button>
                <el-button @click="toggleSelectAll">{{ isAllSelected ? '取消全选' : '全选' }}</el-button>
            </div>
        </template>

        <!-- 优化表格 -->
        <el-table v-loading="loading" ref="tableRef"
            :data="filteredTableData.slice((currentPage2 - 1) * pageSize2, currentPage2 * pageSize2)"
            style="width: 100%" border @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="ID" width="120">
                <template #default="scope">{{ scope.row.id }}</template>
            </el-table-column>
            <el-table-column property="name" label="名称" width="120" />
            <el-table-column property="collection" label="收藏" />
            <el-table-column property="likes" label="点赞量" width="120" />
            <el-table-column property="volume" label="转发量" width="120" />
            <el-table-column label="链接">

            </el-table-column>
            <el-table-column property="time" label="抓取时间" />
            <el-table-column property="cv" label="播放量" />
            <el-table-column property="img" label="图片" width="100">
                <template #default="{ row }">
                    <el-image :src="row.img" :preview-src-list="[row.img]" fit="cover"
                        style="width: 50px; height: 50px" />
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="handleEdit(scope.row.id)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
                    <el-button type="warning" size="small" @click="handleSend(scope.row.id)">发送</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 优化分页 -->
        <div class="pagination-container">
            <el-pagination v-model:current-page="currentPage2" v-model:page-size="pageSize2"
                :page-sizes="[10, 20, 50, 100]" :total="totalCount" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
    </el-card>

    <!-- 保留原有的统计卡片 -->
    <el-card style="margin-top: 20px">
        <el-row :gutter="20">
            <el-col :span="12">
                <div ref="trendChart" style="height: 400px"></div>
            </el-col>
            <el-col :span="12">
                <div ref="pieChart" style="height: 400px"></div>
            </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 20px">
            <el-col :span="24">
                <div ref="barChart" style="height: 400px"></div>
            </el-col>
        </el-row>
    </el-card>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useTransition } from '@vueuse/core'
import * as echarts from 'echarts'
import { ChatLineRound, Male } from '@element-plus/icons-vue'
const filteredTableData = ref([])
const previewData = ref([])
import { mockApi } from './crawler.js'
import request from '@/utils/request'
const searchForm = ref({
    name: '',
    timeRange: []
})
const loading = ref(false)
const selectedRows = ref([])
const currentPage2 = ref(1)
const tableRef = ref(null)
const pageSize2 = ref(5)
const totalCount = ref(0)
const isAllSelected = ref(false)
const loadPreviewData = async () => {
    try {
        const data = await mockApi.getPreviewData()
        previewData.value = data.data
        updateCharts(data.data) // 更新图表
    } catch (error) {
        ElMessage.error('加载预览数据失败')
    }
}


// 获取数据
const getList = async () => {
    loading.value = true
    try {
        const res = await request.get('/users')
        filteredTableData.value = res
        totalCount.value = res.length
        console.log(res);
    } catch (error) {
        ElMessage.error('获取数据失败')
    } finally {
        loading.value = false
    }
}

// 处理搜索
const handleSearch = () => {
    currentPage2.value = 1
    getList()
}

// 重置搜索
const resetSearch = () => {
    searchForm.value = {
        name: '',
        timeRange: []
    }
    handleSearch()
}

// 处理删除
const handleDelete = async (id) => {
    try {
        await ElMessageBox.confirm('确认删除该记录吗？', '提示', {
            type: 'warning'
        })
        await request.delete(`/users/${id}`)
        ElMessage.success('删除成功')
        getList()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败')
        }
    }
}

// 批量删除
const handleBatchDelete = async () => {
    try {
        await ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 条记录吗？`, '提示', {
            type: 'warning'
        })
        // 实现批量删除逻辑
        ElMessage.success('批量删除成功')
        getList()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('批量删除失败')
        }
    }
}

// 处理表格选择变化
const handleSelectionChange = (rows) => {
    selectedRows.value = rows
}

// 分页处理
const handleSizeChange = (val) => {
    pageSize2.value = val
    getList()
}

const handleCurrentChange = (val) => {
    currentPage2.value = val
    getList()
}
// 处理批量发送
const handleBatchSend = async () => {
    try {
        await ElMessageBox.confirm(`确认发送选中的 ${selectedRows.value.length} 条记录吗？`, '提示', {
            type: 'warning'
        })
        // 这里添加实际的批量发送逻辑
        ElMessage.success('批量发送成功')
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('批量发送失败')
        }
    }
}

// 导出功能
const handleExport = () => {
    // 实现导出逻辑
    ElMessage.success('导出成功')
}

const source = ref(0)
const source1 = ref(0)
const outputValue = useTransition(source, {
    duration: 1500,
})
source.value = 386
const outputValue1 = useTransition(source1, {
    duration: 1500,
})
source1.value = 12

onMounted(() => {
    getList()
    loadPreviewData()
})

const trendChart = ref(null)
const pieChart = ref(null)
const barChart = ref(null)

// 初始化图表
const updateCharts = (data) => {
    // 趋势图
    const trendChartInstance = echarts.init(trendChart.value)
    const trendOption = {
        title: {
            text: '数据趋势'
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['播放量', '点赞量', '转发量', '收藏量']
        },
        xAxis: {
            type: 'category',
            data: data.map(item => item.nickname)
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '粉丝数',
                type: 'bar',
                data: data.map(item => parseInt(item.followers.replace('w', '')) * 10000) // 将粉丝数转换为数字
            },
            {
                name: '获赞数',
                type: 'bar',
                data: data.map(item => parseInt(item.likes.replace('w', '')) * 10000) // 将获赞数转换为数字
            }
        ]
    }
    trendChartInstance.setOption(trendOption)

    // 饼图
    const pieChartInstance = echarts.init(pieChart.value)
    const pieOption = {
        title: {
            text: '数据分布'
        },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            left: 'left'
        },
        series: [
            {
                name: '数据占比',
                type: 'pie',
                radius: ['50%', '70%'],
                avoidLabelOverlap: false,
                label: {
                    show: true,
                    position: 'outside'
                },
                data: [
                    { value: sumData('cv'), name: '播放量' },
                    { value: sumData('likes'), name: '点赞量' },
                    { value: sumData('volume'), name: '转发量' },
                    { value: sumData('collection'), name: '收藏量' }
                ]
            }
        ]
    }
    pieChartInstance.setOption(pieOption)
}

// 计算数据总和的辅助函数
const sumData = (key) => {
    return filteredTableData.value.reduce((sum, item) => sum + (Number(item[key]) || 0), 0)
}
// onMounted(() => {
//     // 在获取数据后初始化图表
//     getList().then(() => {
//         if (filteredTableData.value.length > 0) {
//             initCharts()
//         }
//     })
// })
</script>

<style scoped>
.search-card {
    margin-bottom: 16px;
}

.table-card {
    margin-bottom: 16px;
}

.table-header {
    display: flex;
    gap: 16px;
}

.pagination-container {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
}

.el-col {
    text-align: center;
}
</style>
